package org.rsbot.gui;

import java.awt.AWTKeyStroke;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.TrayIcon.MessageType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.swing.ImageIcon;

import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.lazygamerz.scripting.api.Environment;

import org.rsbot.bot.Bot;
import org.rsbot.script.Script;
import org.rsbot.script.ScriptManifest;
import org.rsbot.script.ScriptHandler;
import org.rsbot.script.internal.event.ScriptListener;
import org.rsbot.util.GlobalConfiguration;
import org.rsbot.util.ScreenshotUtil;

public class BotGUI extends JFrame implements ActionListener, ScriptListener {

    public static final int PANEL_WIDTH = 765, PANEL_HEIGHT = 502, LOG_HEIGHT = 120;
    private static final long serialVersionUID = -2678464873236578L;
    private static final Logger log = Logger.getLogger(BotGUI.class.getName());
    public static final Map<String, String> themes = new HashMap<String, String>();
    private ConsolePanel consolePanel = null;
    private JTabbedPane ClientWindows;
    public ScriptEditor scriptEditor;
    public LogGUI logGUI;
    private BotPanel panel;
    private BotToolBar toolBar;
    private BotMenuBar menuBar;
    private BotHome home;
    private TrayIcon trayIcon;
    private static MenuItem hideShow;
    private List<Bot> bots = new ArrayList<Bot>();
    public String did ="";

    public BotGUI() {
        init();
        setTitle(null);
        setLocationRelativeTo(getOwner());
        setMinimumSize(getSize());
        setResizable(true);
    }

    @Override
    public void setTitle(String title) {
        if (title != null) {
            super.setTitle(title + " - " + GlobalConfiguration.NAME + " v"
                    + ((float) GlobalConfiguration.getVersion() / 100) + " [Beta]");
        } else {
            super.setTitle(GlobalConfiguration.NAME + " v"
                    + ((float) GlobalConfiguration.getVersion() / 100) + " [Beta]");
        }
    }

    public void actionPerformed(ActionEvent evt) {
        String action = evt.getActionCommand();
        String menu;
        String[] option = new String[2];
        int z = action.indexOf('.');
        if (z == -1) {
            menu = action;
            option[1] = "";
        } else {
            menu = action.substring(0, z);
            option[1] = action.substring(z + 1);
        }
        //if (menu.equals("Close")) {
        //int idx = Integer.parseInt(option);
        //removeBot(bots.get(idx - 1));
        //} else
        if (menu.equals("Client")) {
            Bot current = getCurrentBot();
            if (current != null) {
                if (option[1].equals("Accounts")) {
                    ScreenshotUtil.takeScreenshot(current, current.getMethods().isLoggedIn());
                    AccountManager.getInstance().showGUI();
                    //if (option.equals("New Bot")) {
                    //addBot();
                    //} else if (option.equals("Close Bot")) {
                    //removeBot(getCurrentBot());
                } else if (option[1].equals("Run Script")) {
                    showScriptSelector(current);
                } else if (option[1].equals("Stop Script")) {
                    showStopScript(current);
                } else if (option[1].equals("Pause Script")) {
                    pauseScript(current);
                } else if (option[1].equals("Force Input")) {
                    boolean selected = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                    current.overrideInput = selected;
                    toolBar.setOverrideInput(selected);
                } else if (option[1].equals("Less CPU")) {
                    current.disableRendering = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Exit")) {
                    System.exit(0);
                }
            }
        } else if (menu.equals("Screen Shots")) {
            Bot current = getCurrentBot();
            if (current != null) {
                if (option[1].equals("Save ScreenShot")) {
                    ScreenshotUtil.saveScreenshot(current, current.getMethods().isLoggedIn());
                } else if (option[1].equals("Save ScreenShot (UnCen)")) {
                    ScreenshotUtil.saveScreenshot(current, false);
                }
            }
        } else if (menu.equals("Anti-Bans")) {
            Bot current = getCurrentBot();
            if (current != null) {
                if (option[1].equals("Disable All Anti-Bans")) {
                    current.disableAntibans = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Auto Login")) {
                    current.disableAutoLogin = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Break Handler")) {
                    current.disableBreakHandler = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                }
            }
        } else if (menu.equals("Randoms")) {
            Bot current = getCurrentBot();
            if (current != null) {
                if (option[1].equals("Disable All Random Solving")) {
                    current.disableRandoms = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Bee Hive")) {
                    current.disableBeehiveSolver = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Capn Arnav")) {
                    current.disableCapnArnav = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Certer")) {
                    current.disableCerter = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Drill Demon")) {
                    current.disableDrillDemon = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Exam")) {
                    current.disableExam = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable First Time Death")) {
                    current.disableFirstTimeDeath = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Freaky Forester")) {
                    current.disableFreakyForester = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Frog Cave")) {
                    current.disableFrogCave = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Grave Digger")) {
                    current.disableGraveDigger = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Leave Safe Area")) {
                    current.disableLeaveSafeArea = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Lost And Found")) {
                    current.disableLostAndFound = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Maze")) {
                    current.disableMaze = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Mime")) {
                    current.disableMime = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Molly")) {
                    current.disableMolly = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Pillory")) {
                    current.disablePillory = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Pinball")) {
                    current.disablePinball = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Prison")) {
                    current.disablePrison = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Quiz Solver")) {
                    current.disableQuizSolver = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Sandwhich Lady")) {
                    current.disableSandwhichLady = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                } else if (option[1].equals("Disable Scape Rune Island")) {
                    current.disableScapeRuneIsland = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
                }
            }
        } else if (menu.equals("Hide")) {
            boolean selected = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
            if (option[1].equals("Hide Toolbar")) {
                toggleViewStateHi(toolBar, selected);
            } else if (option[1].equals("Hide Option Buttons")) {
                toggleViewState(getConsolePanel().toolPanel1, selected);
            } else if (option[1].equals("Hide Option Console")) {
                toggleViewStateWi(getConsolePanel(), selected);
            }
        } else if (menu.equals("Debug")) {
            Bot current = getCurrentBot();
            boolean selected = ((JCheckBoxMenuItem) evt.getSource()).isSelected();
            if (current != null) {
                if (option[1].equals("All Debugging")) {
                    for (String key : BotMenuBar.DEBUG_MAP.keySet()) {
                        Class<?> el = BotMenuBar.DEBUG_MAP.get(key);
                        boolean wasSelected = menuBar.getCheckBox(key).isSelected();
                        menuBar.getCheckBox(key).setSelected(selected);
                        if (selected) {
                            if (!wasSelected) {
                                current.addListener(el);
                            }
                        } else {
                            if (wasSelected) {
                                current.removeListener(el);
                            }
                        }
                    }
                } else {
                    Class<?> el = BotMenuBar.DEBUG_MAP.get(option[1]);
                    menuBar.getCheckBox(option[1]).setSelected(selected);
                    if (selected) {
                        current.addListener(el);
                    } else {
                        menuBar.getCheckBox("All Debugging").setSelected(false);
                        current.removeListener(el);
                    }
                }
            }
        } else if (menu.equals("Skins")) {
            setTheme(option[1]);
        } else if (menu.equals("Help")) {
            if (option[1].equals("Troubleshooting")) {
                openURL("http://www.runedev-infinity.org/forums/index.php?board=11.0");
            } else if (option[1].equals("Site")) {
                openURL(GlobalConfiguration.Paths.URLs.SITE);
            } else if (option[1].equals("Forums")) {
                openURL("http://www.runedev-infinity.org/forums/index.php");
            } else if (option[1].equals("Wiki")) {
                openURL("http://runedev.wikia.com/wiki/RuneDev_Wiki");
            } else if (option[1].equals("Facebook")) {
                openURL("http://www.facebook.com/pages/Runedevinfo/144013358963281");
            } else if (option[1].equals("Project")) {
                openURL(GlobalConfiguration.Paths.URLs.PROJECT);
            } else if (option[1].equals("The Client")) {
                JOptionPane.showMessageDialog(this, new String[]{"An open source Client.", "Developed by a hands on team\n" + "Who works closely with the community\n" + "For more information, visit\n" + GlobalConfiguration.Paths.URLs.SITE}, "About the Clinet", JOptionPane.INFORMATION_MESSAGE);
            } else if (option[1].equals("The Makers")) {
                openURL("http://code.google.com/p/noipdevteam/wiki/Aboutthemakers?ts=" + "1268920860&updated=Aboutthemakers");
            }
        } else if (menu.equals("Tab")) {
            Bot curr = getCurrentBot();
            menuBar.setBot(curr);
            panel.setBot(curr);
            panel.repaint();
            toolBar.setHome(curr == null);
            if (curr == null) {
                setTitle(null);
                toolBar.setScriptButton(BotToolBar.RUN_SCRIPT);
                toolBar.setOverrideInput(false);
                toolBar.setInputState(Environment.inputKeyboard | Environment.inputMouse);
            } else {
                setTitle(curr.getAccountName());
                Map<Integer, Script> scriptMap = curr.getScriptHandler().getRunningScripts();
                if (scriptMap.size() > 0) {
                    if (scriptMap.values().iterator().next().isPaused()) {
                        toolBar.setScriptButton(BotToolBar.RESUME_SCRIPT);
                    } else {
                        toolBar.setScriptButton(BotToolBar.PAUSE_SCRIPT);
                    }
                } else {
                    toolBar.setScriptButton(BotToolBar.RUN_SCRIPT);
                }
                toolBar.setOverrideInput(curr.overrideInput);
                toolBar.setInputState(curr.inputFlags);
            }
        } else if (menu.equals("Run")) {
            Bot current = getCurrentBot();
            if (current != null) {
                showScriptSelector(current);
            }
        } else if (menu.equals("Pause") || menu.equals("Resume")) {
            Bot current = getCurrentBot();
            if (current != null) {
                pauseScript(current);
            }
        } else if (menu.equals("Input")) {
            Bot current = getCurrentBot();
            if (current != null) {
                boolean override = !current.overrideInput;
                current.overrideInput = override;
                menuBar.setOverrideInput(override);
                toolBar.setOverrideInput(override);
                toolBar.updateInputButton();
            }
        }
    }

    public BotPanel getPanel() {
        return panel;
    }

    public Bot getBot(Object o) {
        ClassLoader cl = o.getClass().getClassLoader();
        for (Bot bot : bots) {
            if (cl == bot.getLoader().getClient().getClass().getClassLoader()) {
                panel.offset();
                return bot;
            }
        }
        return null;
    }

    public void addBot() {
        final Bot bot = new Bot();
        bots.add(bot);
        toolBar.addTab();
        bot.getScriptHandler().addScriptListener(this);
        new Thread(new Runnable() {

            public void run() {
                bot.start();
                home.setBots(bots);
            }
        }).start();
    }

    public void removeBot(final Bot bot) {
        int idx = bots.indexOf(bot);
        if (idx >= 0) {
            toolBar.removeTab(idx + 1);
        }
        bots.remove(idx);
        bot.getScriptHandler().stopAllScripts();
        bot.getScriptHandler().removeScriptListener(this);
        home.setBots(bots);
        new Thread(new Runnable() {

            public void run() {
                bot.stop();
                System.gc();
            }
        }).start();
    }

    void pauseScript(Bot bot) {
        ScriptHandler sh = bot.getScriptHandler();
        Map<Integer, Script> running = sh.getRunningScripts();
        if (running.size() > 0) {
            int id = running.keySet().iterator().next();
            sh.pauseScript(id);
        }
    }

    public Bot getCurrentBot() {
        int idx = toolBar.getCurrentTab() - 1;
        if (idx >= 0) {
            return bots.get(idx);
        }
        return null;
    }

    private void showScriptSelector(Bot bot) {
        if (AccountManager.getAccountNames().length == 0) {
            JOptionPane.showMessageDialog(this, "No accounts found! Please create one before using the bot.");
            AccountManager.getInstance().showGUI();
        } else if (bot.getMethods() == null) {
            JOptionPane.showMessageDialog(this, "The client is not currently loaded!");
        } else {
            ScriptSelector.getInstance(this).showSelector();
        }
    }

    private void showStopScript(Bot bot) {
        ScriptHandler sh = bot.getScriptHandler();
        Map<Integer, Script> running = sh.getRunningScripts();
        if (running.size() > 0) {
            int id = running.keySet().iterator().next();
            Script s = running.get(id);
            ScriptManifest prop = s.getClass().getAnnotation(ScriptManifest.class);
            int result = JOptionPane.showConfirmDialog(this,
                    "Would you like to stop the script " + (prop == null ? s.getClass().getName() : prop.name()) + "?",
                    "Script", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (result == JOptionPane.OK_OPTION) {
                sh.stopScript(id);
                toolBar.setScriptButton(BotToolBar.RUN_SCRIPT);
            }
        }
    }

    private void toggleViewState(Component component, boolean visible) {
        Dimension size = getSize();
        component.setVisible(!visible);
        setMinimumSize(size);
        if ((getExtendedState() & Frame.MAXIMIZED_BOTH) != Frame.MAXIMIZED_BOTH) {
            pack();
        }
    }

    private void toggleViewStateHi(Component component, boolean visible) {
        Dimension size = getSize();
        size.height += component.getSize().height * (visible ? -1 : 1);
        component.setVisible(!visible);
        setMinimumSize(size);
        if ((getExtendedState() & Frame.MAXIMIZED_BOTH) != Frame.MAXIMIZED_BOTH) {
            pack();
        }
    }

    private void toggleViewStateWi(Component component, boolean visible) {
        Dimension size = getSize();
        size.width += component.getSize().width * (visible ? -1 : 1);
        component.setVisible(!visible);
        setMinimumSize(size);
        if ((getExtendedState() & Frame.MAXIMIZED_BOTH) != Frame.MAXIMIZED_BOTH) {
            pack();
        }
    }

    private void init() {
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

        addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                dispose();
                System.exit(0);
            }
        });

        setIconImage(GlobalConfiguration.getImage(
                GlobalConfiguration.Paths.Resources.ICON,
                GlobalConfiguration.Paths.ICON));

        JPopupMenu.setDefaultLightWeightPopupEnabled(false);

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (final Exception ignored) {
        }

        themes.put("RuneDev", "de.muntjak.tinylookandfeel.TinyLookAndFeel");
        themes.put("System", UIManager.getSystemLookAndFeelClassName());
        themes.put("Quirlion", "com.nilo.plaf.nimrod.NimRODLookAndFeel");
        themes.put("Windows", "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        themes.put("Aero", "com.jtattoo.plaf.aero.AeroLookAndFeel");
        themes.put("Aluminium", "com.jtattoo.plaf.aluminium.AluminiumLookAndFeel");
        themes.put("Hifi", "com.jtattoo.plaf.hifi.HiFiLookAndFeel");

        home = new BotHome();
        panel = new BotPanel(home);
        toolBar = new BotToolBar(this);
        menuBar = new BotMenuBar(this);
        panel.setFocusTraversalKeys(0, new HashSet<AWTKeyStroke>());
        toolBar.setHome(true);
        menuBar.setBot(null);
        setJMenuBar(menuBar);

        ClientWindows = new JTabbedPane();
        scriptEditor = new ScriptEditor();
        logGUI = new LogGUI();
        try {
            ClientWindows.setFont(new Font("Futura Md BT", 0, 10));
            ClientWindows.addTab("Game Window", new ImageIcon(GlobalConfiguration.RUNNING_FROM_JAR
                    ? getClass().getResource(GlobalConfiguration.Paths.Resources.ENF)
                    : new File(GlobalConfiguration.Paths.ENF).toURI().toURL()), panel);
        } catch (final MalformedURLException e1) {
        }

        try {
            ClientWindows.setFont(new Font("Futura Md BT", 0, 10));
            ClientWindows.addTab("Script Editor", new ImageIcon(GlobalConfiguration.RUNNING_FROM_JAR
                    ? getClass().getResource(GlobalConfiguration.Paths.Resources.ENF)
                    : new File(GlobalConfiguration.Paths.ENF).toURI().toURL()), scriptEditor);
        } catch (final MalformedURLException e1) {
        }

        try {
            ClientWindows.setFont(new Font("Futura Md BT", 0, 10));
            ClientWindows.addTab("Log", new ImageIcon(GlobalConfiguration.RUNNING_FROM_JAR
                    ? getClass().getResource(GlobalConfiguration.Paths.Resources.ENF)
                    : new File(GlobalConfiguration.Paths.ENF).toURI().toURL()), logGUI);
        } catch (final MalformedURLException e1) {
        }

        add(toolBar, BorderLayout.NORTH);
        add(ClientWindows, BorderLayout.WEST);
        add(getConsolePanel(), BorderLayout.EAST);
        pack();
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                trayIcon();
            }
        });
    }

    /**
     * This method initializes consolePanel
     *
     * @return org.rsbot.gui.ConsolePanel
     */
    private ConsolePanel getConsolePanel() {
        if (consolePanel == null) {
            consolePanel = new ConsolePanel();
        }
        return consolePanel;
    }

    private void openURL(final String url) {
        GlobalConfiguration.OperatingSystem os = GlobalConfiguration.getCurrentOperatingSystem();
        try {
            if (os == GlobalConfiguration.OperatingSystem.MAC) {
                Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
                Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[]{String.class});
                openURL.invoke(null, url);
            } else if (os == GlobalConfiguration.OperatingSystem.WINDOWS) {
                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
            } else { // assume Unix or Linux
                String[] browsers = {"firefox", "opera", "konqueror", "epiphany", "mozilla", "netscape"};
                String browser = null;
                for (int count = 0; (count < browsers.length) && (browser == null); count++) {
                    if (Runtime.getRuntime().exec(new String[]{"which", browsers[count]}).waitFor() == 0) {
                        browser = browsers[count];
                    }
                }
                if (browser == null) {
                    throw new Exception("Could not find web browser");
                } else {
                    Runtime.getRuntime().exec(new String[]{browser, url});
                }
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error Opening Browser", "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void scriptStarted(ScriptHandler handler, Script script) {
        Bot bot = handler.getBot();
        if (bot == getCurrentBot()) {
            bot.inputFlags = Environment.inputKeyboard;
            bot.overrideInput = false;
            toolBar.setScriptButton(BotToolBar.PAUSE_SCRIPT);
            toolBar.setInputState(bot.inputFlags);
            toolBar.setOverrideInput(false);
            menuBar.setOverrideInput(false);
            String acct = bot.getAccountName();
            //toolBar.setTabLabel(bots.indexOf(bot) + 1, acct == null ? "RuneScape" : acct);
            toolBar.updateInputButton();
            setTitle(acct);
        }
    }

    public void scriptStopped(ScriptHandler handler, Script script) {
        Bot bot = handler.getBot();
        if (bot == getCurrentBot()) {
            bot.inputFlags = Environment.inputKeyboard | Environment.inputMouse;
            bot.overrideInput = false;
            toolBar.setScriptButton(BotToolBar.RUN_SCRIPT);
            toolBar.setInputState(bot.inputFlags);
            toolBar.setOverrideInput(false);
            menuBar.setOverrideInput(false);
            menuBar.setPauseScript(false);
            //toolBar.setTabLabel(bots.indexOf(bot) + 1, "RuneScape");
            toolBar.updateInputButton();
            setTitle(null);
        }
    }

    public void scriptResumed(ScriptHandler handler, Script script) {
        if (handler.getBot() == getCurrentBot()) {
            toolBar.setScriptButton(BotToolBar.PAUSE_SCRIPT);
            menuBar.setPauseScript(false);
        }
    }

    public void scriptPaused(ScriptHandler handler, Script script) {
        if (handler.getBot() == getCurrentBot()) {
            toolBar.setScriptButton(BotToolBar.RESUME_SCRIPT);
            menuBar.setPauseScript(true);
        }
    }

    public void inputChanged(Bot bot, int mask) {
        bot.inputFlags = mask;
        toolBar.setInputState(mask);
        toolBar.updateInputButton();
    }

    public void runScript(String name, Script script, Map<String, String> args) {
        Bot.setAccount(name);
        Bot.getScriptHandler().runScript(script, args);
    }

    /**
     * Allows for a safe close of the client by
     * @return
     */
    private boolean safeClose() {
        boolean pass = true;
        if (Bot.methods.isLoggedIn()) {
            final int result = JOptionPane.showConfirmDialog(this, "Are you sure you would like to quit?", "Close", JOptionPane.WARNING_MESSAGE, JOptionPane.YES_NO_OPTION);
            pass = result == JOptionPane.YES_OPTION;
        }
        return pass;
    }

    /**
     * Sets the names of the themes into the skins menu
     * @param Name      The name of the UIManger theme
     */
    void setTheme(final String Name) {
        for (final String key : themes.keySet()) {
            final boolean match = key.equals(Name);
            if (match) {
                try {
                    UIManager.setLookAndFeel(themes.get(key));
                } catch (final Exception e) {
                }
                for (Frame frame : BotGUI.getFrames()) {
                    SwingUtilities.updateComponentTreeUI(frame);
                    frame.pack();

                }

            }
            menuBar.getCheckBox(key).setSelected(match);
        }
    }

    private void trayIcon() {
        if (SystemTray.isSupported()) {
            final SystemTray tray = SystemTray.getSystemTray();
            final Image icon = GlobalConfiguration.getImage(GlobalConfiguration.Paths.Resources.ICON, GlobalConfiguration.Paths.ICON);
            final ActionListener exitListener = new ActionListener() {

                public void actionPerformed(final ActionEvent e) {
                    BotGUI.log.info("Exiting...");
                    System.exit(0);
                }
            };

            final ActionListener rightClickListener = new ActionListener() {

                public void actionPerformed(final ActionEvent e) {
                    final String msg = "You have controled the view of the client by\n"
                            + "right clicking on the system tray icon,\n"
                            + "and chosing the control client view option.\n"
                            + "To again toggle the view state of the client,\n"
                            + "simply click the system tray icon again.";
                    trayIcon.displayMessage("Controling, " + getTitle(), msg, MessageType.INFO);
                    setVisible(!isVisible());
                }
            };

            final ActionListener clickListener = new ActionListener() {
                public void actionPerformed(final ActionEvent e) {

                    final String msg = "You have controled the view of the client by,\n"
                            + "clicking on the system tray icon.\n"
                            + "To again toggle the view state of the client,\n"
                            + "simply click the system tray icon again.";
                    trayIcon.displayMessage("Controling, " + getTitle(), msg, MessageType.INFO);
                    setVisible(!isVisible());

                }
            };

            final PopupMenu popup = new PopupMenu();
            final MenuItem exitOption = new MenuItem("Exit Client");
            exitOption.addActionListener(exitListener);
            final MenuItem hideTaskBarIcon = new MenuItem("Control Client View");
            hideTaskBarIcon.addActionListener(rightClickListener);

            popup.add(hideTaskBarIcon);
            popup.add(exitOption);

            trayIcon = new TrayIcon(icon, getTitle(), popup);
            trayIcon.setImageAutoSize(true);
            trayIcon.addActionListener(clickListener);

            try {
                tray.add(trayIcon);
            } catch (final Exception e) {
                BotGUI.log.warning("System tray could not be created.");
            }
        } else {
            BotGUI.log.warning("System tray is not supported.");

        }

    }
}
